package com.kdtech.analyse.Bbs.common;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
/**
 * 基于Invision Power Board (IP.Board)的论坛模板解析
 *
 * Powered by Invision Power Board
 *
 * 0000
 * http://bbs.chinacourt.org/index.php 法治论坛
 * @author KK
 */
public class BbsAnalyseIPB implements AnalyseNews {


	
	public boolean isDetailPage(String url) {
		url = UrlArgumentTop.FromatUrl(url);
		url = StringUtils.substringAfterLast(url, "/");
		String[] regex = {
//				"index.php\\?showtopic=[0-9]*&s=[a-z0-9]*",
				"index.php\\?showtopic=[0-9]*",
				"index.php\\?showtopic=[0-9]*&st=[0-9]*",
				"index.php\\?showtopic=[0-9]*&view=.*"
				};
		return RegexUtils.matchAny(url, regex);
	}

	public NewsMeta parserHtml(UrlMeta urlMeta) {

		if (urlMeta.getHtml() == null) {
			return null;
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();

		String title = null;
		String content = null;
		Long date = null;
		Integer commnetNum = null;
		Integer clickNum = null;
		String updateUrl = url;
		String author=null;
		Document doc = Jsoup.parse(htmltxt);

		title = doc.select("td.maintitle b").text();
		if(StringUtils.isBlank(title)){
			title = doc.select("div.maintitle b").text();
		}
		doc.select("a:containsOwn(登录/注册后可看大图)").remove();
		date = DateUtils.matchDate(doc.select("span.postdetails").text());
		Element first = doc.select("div.postcolor").first();
		content = HtmlCleaner.getContentHtml(url,first);
		 first = doc.select("span.normalname").first();
		if(first!=null){
			author = first.text();
		}

			NewsMeta news = new NewsMeta();
			news.setUrl(url);
			news.setType(4);
			news.setTitle(StringUtils.trimSpace(title));
			news.setCommentNum(commnetNum);
			news.setClickNum(clickNum);
			news.setContent(StringUtils.trimSpace(content));
			news.setDate(date);
			news.setAuthor(author);
			news.setUpdateUrl(updateUrl);
			return news;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}

	

	

}
